#!/usr/bin/perl -w
use strict;
###  Take as arguments the genome and cell type for these
if(scalar(@ARGV) < 2) { die "cat ctcf.bed | ./find_ctcf_bounds.pl hg18 Nhek\nProvide 2 arguments, the genome and cell type.\n"; }
my $genome = shift(@ARGV);
my $celltype = shift(@ARGV);

chomp(my @lines = <STDIN>);
my %chromosomes;
foreach my $line (@lines) {
  my @fields = split(/\t/,$line);
  my $midpoint = int(($fields[2]+$fields[1])/2);
  if(!exists($chromosomes{$fields[0]})) {  
    my @hits;
    $chromosomes{$fields[0]} = \@hits;
    push @{$chromosomes{$fields[0]}}, $fields[1];
  } else {
    push @{$chromosomes{$fields[0]}}, $fields[1];
  }
}  
foreach my $chromosome (keys(%chromosomes)) {
  my @hits = @{$chromosomes{$chromosome}};
  push @hits, 10000000000; #upper bound
  unshift @hits, 0; #lower bound
  for(my $i=0; $i < scalar(@hits)-1; $i++) {
    print "$genome\t$celltype\t$chromosome\t$hits[$i]\t$hits[$i+1]\n";
  }
}
